/**转岗培训的列表页面 */
<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.trainerName" placeholder="培训人" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.traineeName" placeholder="受训人" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.oldTeamName" placeholder="原所属Team" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.newTeamName" placeholder="现所属Team" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.subject" placeholder="主题" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.sdate" placeholder="开始时间" style="width: 200px;" class="filter-item" type="date" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.edate" placeholder="结束时间" style="width: 200px;" class="filter-item" type="date" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="checkPermission(['postadd'])" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-clean" @click="handleReset">
        重置
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">
      <el-table-column width="180px" align="center" label="培训编号" prop="id" />

      <el-table-column min-width="300px" label="培训主题">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.subject }}</span></template>
      </el-table-column>
      <el-table-column min-width="100px" label="培训等级">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.levels==1? '班组培训':'车间培训' }}</span></template>
      </el-table-column>
        <el-table-column width="100px" label="培训开始时间">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.sdate}}</span></template>
      </el-table-column>

      <el-table-column width="100px" label="培训结束时间">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.edate}}</span></template>
      </el-table-column>
      <el-table-column align="center" label="培训人" width="95">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.trainer.userName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="受训人" width="95">
        <template slot-scope="scope">
          <span>{{ scope.row.trainee==null? ' ':scope.row.trainee.userName }}</span></template>
      </el-table-column>
       <el-table-column class-name="status-col" label="原所属Team" width="110">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.oldDept.deptName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="现所属Team" width="100">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.newDept==null? ' ':scope.row.newDept.deptName }}</span></template>
      </el-table-column>
      <el-table-column class-name="status-col" label="附件" width="110">
        <template slot-scope="scope">
          <el-button v-if="scope.row.flagFile== 1" type="primary" size="small" @click="handlegetFile(scope.row)">附件</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分数" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.grade }}</span></template>
      </el-table-column>
       <el-table-column align="center" label="审核状态" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.astatus==0">申请中..</span>
          <span v-if="scope.row.astatus==1">已通过</span>
          <span v-if="scope.row.astatus==-1">已驳回</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核意见" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.auditinf }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="审核时间">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.odate }}</span></template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="230">
        <template slot-scope="scope">
          <el-button v-if="scope.row.astatus==-1" type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.astatus==-1" type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="hidden" label="培训编号" prop="id">
          <el-input v-model="temp.id" readonly />
        </el-form-item>
        <el-form-item label="培训主题" :required="!isRequired" prop="subject">
          <el-input v-model="temp.subject" />
        </el-form-item>
         <el-form-item label="培训级别" :required="!isRequired" prop="levels">
          <el-select v-model="temp.levels" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
       <el-form-item label="培训开始时间" :required="!isRequired" prop="sdate">
          <el-date-picker v-model="temp.sdate" type="datetime" format="yyyy-MM-dd hh:mm:ss" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择一个日期" />
        </el-form-item>
        <el-form-item label="培训结束时间" :required="!isRequired" prop="edate">
          <el-date-picker v-model="temp.edate" type="datetime" format="yyyy-MM-dd hh:mm:ss" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择一个日期" />
        </el-form-item>
        <el-form-item label="培训人" prop="trainer">
          <el-input v-model="userName1" readonly="readonly" placeholder="不填"/>
        </el-form-item>
        <el-form-item label="受训人" :required="!isRequired" >
          <el-autocomplete
            v-model="userName2"
            class="el-input"
            :fetch-suggestions="userSearchAsyncE"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelectE"
          />
        </el-form-item>
        <el-form-item label="原所属Team" :required="!isRequired">
          <el-select v-model="deptName1" class="filter-item" placeholder="请选择">
            <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="现所属Team" :required="!isRequired">
          <el-select v-model="deptName2" class="filter-item" placeholder="请选择">
            <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="学时" prop="period" :required="!isRequired" >
          <el-input v-model="temp.period" />
        </el-form-item>
        <el-form-item label="分数" prop="grade">
          <el-input v-model="temp.grade" />
        </el-form-item>
        <el-form-item label="培训内容" prop="content">
          <el-input v-model="temp.content" type="textarea" />
        </el-form-item>
        <el-form-item label="附件上传">
          <ul>
            <div style="margin-left:100px">
              <el-upload
                v-model="file"
                class="upload-demo"
                action="http://localhost:8080/ehs_files/upload"
                :on-change="handleChange"
                :on-success="uploadfile"
              ><el-button size="big" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </ul>.
        </el-form-item>
        <el-form-item label="审核人" :required="!isRequired" >
          <el-autocomplete
            v-model="userName3"
            class="el-input"
            :fetch-suggestions="userSearchAsyncA"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelectA"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ElDragSelect from '@/components/DragSelect' // base on element-ui
import MarkdownEditor from '@/components/MarkdownEditor'
import { fetchTrainPostList, deleteTrainPostList, editTrainPost, createTrainPost, fetchAllCount, getPersonList, getDeptList } from '@/api/train-post'
import Sortable from 'sortablejs'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getuserbyemp } from '@/api/user'
import checkPermission from '@/utils/permission'
import { getFileName } from '@/api/file'
export default {
  name: 'TrainPost',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isRequired: false,
      hidden: false,
      id: '',
      type: 'ehs_train_post',
      file: null,
      limitNum: 1,
      formLabelWidth: '80px',
      fileList: [],


      list: null,
      total: 0,
      listLoading: true,
      editList: null,
      userName1: null,
      userName2: null,
      userName3: null,
      userId2: null,
      userId3: null,
      deptName1: null,
      deptName2: null,
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20,
        subject: null,
        trainerName: null,
        traineeName: null,
        oldTeamName: null,
        newTeamName: null,
        sdate: null,
        edate: null
      },
      personlist: null,
      deptlist: null,
      options: [{ value: 1, label: '班组培训' }, { value: 2, label: '车间培训' }],
      temp: {
        id: undefined,
        subject: '',
        sdate: '',
        edate: '',
        satus: 1,
        period: '',
        content: '',
        grade: '',
        levels: '',
        trainer: '',
        trainee: '',
        auditor: '',
        oldDept: '',
        newDept: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        detail: '明细'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'sdate', required: true, message: 'timestamp is required', trigger: 'change' }],
       // timestamp: [{ type: 'edate', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
       getPersonList().then(response => {
        this.personlist = response.listName
      })
      getDeptList().then(response => {
        this.deptlist = response.listName
      })
      fetchAllCount().then(response => {
        this.total = response.count
      })
      fetchTrainPostList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.ehstrainpostList
        this.showList = response.ehstrainpostList
        this.listLoading = false
      })
    },
    checkPermission,
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
      })
    },
     createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const userName1 = this.userName1
          const userName2 = this.userName2
          const userName3 = this.userName3
          const userId2 = this.userId2
          const userId3 = this.userId3
          const deptName1 = this.deptName1
          const deptName2 = this.deptName2
          if(userName2 == null){
            alert("提示：受训人不能为空")
          } else if(deptName1 == null){
            alert("提示：原所属Team不能为空")
          } else if(deptName2 == null){
            alert("提示：现所属Team不能为空")
          } else if(userName3 == null){
            alert("提示：审核人不能为空")
          } else{
          if (this.file == null) {
            const query =
          { sdate: this.temp.sdate,
            edate: this.temp.edate,
            subject: this.temp.subject,
            levels: this.temp.levels,
            userName1: userName1,
            userName2: userName2,
            userName3: userName3,
            userId2: userId2,
            userId3: userId3,
            deptName1: deptName1,
            deptName2: deptName2,
            period: this.temp.period,
            grade: this.temp.grade,
            content: this.temp.content }
            createTrainPost(query).then(() => {
            this.list.unshift(this.temp.userName1)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          } else{
            const query =
          { fileName: this.file.name, 
            fileId: this.file.filesId,
            sdate: this.temp.sdate,
            edate: this.temp.edate,
            subject: this.temp.subject,
            levels: this.temp.levels,
            userName1: userName1,
            userName2: userName2,
            userName3: userName3,
            userId2: userId2,
            userId3: userId3,
            deptName1: deptName1,
            deptName2: deptName2,
            period: this.temp.period,
            grade: this.temp.grade,
            content: this.temp.content }
            createTrainPost(query).then(() => {
            this.list.unshift(this.temp.userName1)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          }
          location.reload()
          }
        }
      })
    },

     // 受训人
    async userSearchAsyncE(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userId = r.userId
        tem_obj.userName = r.userName
        list.push(tem_obj)
      })
      callback(list)
    },
    async handleSelectE(u) {
      this.userName2 = u.userName + ''
      this.userId2 = u.userId + ''
    },

    // 审核人
    async userSearchAsyncA(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userId = r.userId
        tem_obj.userName = r.userName
        list.push(tem_obj)
      })
      callback(list)
    },
    async handleSelectA(u) {
      this.userName3 = u.userName + ''
      this.userId3 = u.userId + ''
    },

     handlegetFile(row) {
      
      this.id = row.id
      this.type = 'ehs_train_post'

      const query = { id: this.id, type: this.type }
      // 获取附件名称
      getFileName(query).then(response => {
        this.file = response.file
        const url = 'http://localhost:8080/ehs_files/getfile?id=' + this.id + '&type=' + this.type // 创建下载链接
        const link = document.createElement('a') // 创建a标签
        link.style.display = 'none' // 将a标签隐藏
        link.href = url // 给a标签添加下载链接
        link.setAttribute('download', this.file.filename) // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
        document.body.appendChild(link)
        link.click() // 执行a标签
      })
    },

    handleChange() {

    },
    uploadfile(response, file, fileList) {
      this.file = response.file
    },

    handleDownload() {

      this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['培训编号', '培训主题', '培训等级', '培训开始时间', '培训结束时间', '培训人', '受训人', '原所属Team', '现所属Team', '分数']
          const filterVal = ['id', 'subject', 'levels', 'sdate', 'edate', 'trainer', 'trainee', 'oldDept', 'newDept', 'grade']

          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } if (j === 'edate') {
            return parseTime(v[j])
          } if (j === 'sdate') {
            return parseTime(v[j])
          } if (j === 'trainee') {
            return v[j].userName
          } 
          if (j === 'oldDept') {
            return v[j].deptName
          } if (j === 'newDept') {
            return v[j].deptName
          }
          if (j === 'trainer') {
            return v[j].userName
          } else {
            return v[j]
          }
        }))
      },
    handleReset() {
      this.listQuery = {
        sdate: '',
        edate: '',
        oldTeamName: null,
        newTeamName: null,
        traineeName: null
      }
    },
    showReviewer() {

    },
    handleFilter() {
      this.listQuery.page = 1
      this.fechData()
    },
    handleDelete(row) {
      {
      this.$confirm('确定删除?', 'Warning', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async() => {
            deleteTrainPostList(row.id).then(response => {
            })
            this.fechData()
            this.$message({
              type: 'success',
              message: 'Delete succed!'
            })
       })
          .catch(err => { console.error(err) })
      }
    },

    handleEdit(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) 
      this.userName1 = this.temp.trainer.userName
      this.userName2 = this.temp.trainee.userName
      this.userName3 = this.temp.auditor.userName
      this.userId2 = this.temp.trainee.userId
      this.userId3 = this.temp.auditor.userId
      this.deptName1 = this.temp.oldDept.deptName
      this.deptName2 = this.temp.newDept.deptName
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            if (this.file == null) {
              const query = { id: query1.id,
                            subject: query1.subject,
                            levels: query1.levels,
                            userName1: this.userName1,
                            userName2: this.userName2,
                            userName3: this.userName3,
                            userId2: this.userId2,
                            userId3: this.userId3,
                            deptName1: this.deptName1,
                            deptName2: this.deptName2,
                            sdate: query1.sdate,
                            edate: query1.edate,
                            period: query1.period,
                            grade: query1.grade,
                            content: query1.content }
            editTrainPost(query).then(response => {
              this.obj = response
              this.id = response.id
              this.subject = response.subject
            })
            }else{
              const query = { fileName: this.file.name, 
                            fileId: this.file.filesId,
                            id: query1.id,
                            subject: query1.subject,
                            levels: query1.levels,
                            userName1: this.userName1,
                            userName2: this.userName2,
                            userName3: this.userName3,
                            userId2: this.userId2,
                            userId3: this.userId3,
                            deptName1: this.deptName1,
                            deptName2: this.deptName2,
                            sdate: query1.sdate,
                            edate: query1.edate,
                            period: query1.period,
                            grade: query1.grade,
                            content: query1.content }
            editTrainPost(query).then(response => {
              this.obj = response
              this.id = response.id
              this.subject = response.subject
            })
            }
            
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    handleDetail(row) {
     const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) 
      this.userName1 = this.temp.trainer.userName
      this.userName2 = this.temp.trainee.userName
      this.userName3 = this.temp.auditor.userName
      this.deptName1 = this.temp.oldDept.deptName
      this.deptName2 = this.temp.newDept.deptName
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    
    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
